//package com.cabinet.utils;
//
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.cabinet.common.core.redis.RedisCache;
//import com.cabinet.system.domain.Devices;
//import com.cabinet.system.service.IDevicesService;
//import com.cabinet.mqtt.client.EmqClient;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.http.ResponseEntity;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//@Service
//@Slf4j
//public class DynamicCabinetUtil {
//
//
//    private static final String ReceivedUploadDeviceInfo = "receivedUploadDeviceInfo";
//
//    @Autowired
//    IDevicesService devicesService;
////    @Autowired
////    MpApplicationServiceImpl mpApplicationService;
////
////    @Autowired
////    MpAppConfigServiceImpl mpAppConfigService;
//    @Autowired
//    EmqClient emqClient;
//
//    @Autowired
//    RocketMQService rocketMQService;
//
//    @Autowired
//    RequestUtils requestUtils;
//
//    @Value("${cabinet.masterServerUrl}")
//    String masterServerUrl;
//
//    @Value("${cabinet.masterServerKey}")
//    String masterServerKey;
//    @Autowired
//    IdWorker idWorker;
//
//
//    @Autowired
//    RedisCache redisUtil;
//
//    // 获取要发送mqtt消息
//    public String gMqttMessage(String event, JSONObject params, String refreshToken) throws Exception {
//        JSONObject json = new JSONObject();
//        json.put("uid", "server");
//        json.put("msgid", String.valueOf(idWorker.nextId()));
//        json.put("time", Long.toString(System.currentTimeMillis() / 1000L));
//        json.put("apiv", "1.0");
//        json.put("event", event);
//        json.put("biz", params.toJSONString());
//        String sign = SignUtils.generateSignature(json, refreshToken);
//        json.put("sign", sign);
//        return json.toJSONString();
//    }
//
//    // 处理消息上报
//    public void uploadDeviceInfo(String biz) {
//        try {
//            JSONObject bizContent = JSON.parseObject(biz);
//            String deviceId = bizContent.getString("deviceId");
//            ResponseEntity<String> post = requestUtils.post(masterServerUrl + "/v1/equipment/equipmentConnectServer", bizContent);
//            int statusCodeValue = post.getStatusCodeValue();
//            if (statusCodeValue != 200) {
//                log.error("{} 请求主服务器失败", biz);
//                return;
//            }
//            String body = post.getBody();
//            log.info("请求主服务器成功,{}", body);
//            JSONObject jsonObject = JSON.parseObject(body);
//            jsonObject.put("refreshToken", jsonObject.get("RK"));
//            Devices devices = devicesService.selectDevicesByDeviceId(deviceId);
//            String mqttMessage = gMqttMessage(ReceivedUploadDeviceInfo, jsonObject, devices.getRefreshToken());
//            emqClient.publish("devices/" + deviceId, mqttMessage);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void handlerCloseTheDoorResult(JSONObject params) {
//        String biz = params.getString("biz");
//        String uid = params.getString("uid");
//        JSONObject json = JSONObject.parseObject(biz);
//        int doorId = json.getInteger("doorId");
//        log.info("删除门锁id:{},deviceId:{}", doorId, uid);
//        redisUtil.del(DevicesServiceImpl.DEVICE_PREFIX + uid + DevicesServiceImpl.DOORID_PREFIX + doorId);
//        Devices device = devicesService.selectDevicesByDeviceId(uid);
//        if (device != null) {
////            MpApplication application = mpApplicationService.getApplicationByAppId(device.getAgentId());
////            if (application != null) {
////                MpAppConfig appConfig = mpAppConfigService.getAppConfigByAppId(device.getAgentId());
////                if (appConfig != null) {
////                    if (!StringUtils.isEmpty(appConfig.getCloseDoorResultCallbackUrl())) {
////                        String orderId = json.getString("orderId");
////                        // 发送关门通知
////                        JSONObject closeObjectResult = new JSONObject();
////                        closeObjectResult.put("deviceId", device.getId());
////                        closeObjectResult.put("doorId", doorId);
////                        closeObjectResult.put("orderId", orderId);
////                        JSONObject closeCallbackMessage = devicesService.getMessage(device, "closeTheDoorResult", closeObjectResult, application.getSecretKey());
////                        rocketMQService.putMQTTMessageToSendUrl(appConfig.getCloseDoorResultCallbackUrl(), closeCallbackMessage);
////                    }
////                }
////                return;
////            }
//        }
//        json.put("key", masterServerKey);
//        rocketMQService.putMQTTMessageToSendUrl(masterServerUrl + "/cabinet/closeTheDoorResult", json);
//    }
//
//    public void handlerCheckTheDoorResult(JSONObject params) {
//        String biz = params.getString("biz");
//        String uid = params.getString("uid");
//        JSONObject json = JSONObject.parseObject(biz);
//        int doorId = json.getInteger("doorId");
//        String orderId = json.getString("orderId");
//        int errCode = json.getInteger("errCode");
//        String rrpcKey = "RRPC:" + uid + ":" + orderId;
//        boolean isSet = redisUtil.set(rrpcKey, 1);
//        if (isSet) {
//            redisUtil.expire(rrpcKey, 60);
//        }
//        if (errCode != 0) {
//            log.info("删除门锁id:{},deviceId:{}", doorId, uid);
//            redisUtil.del(DevicesServiceImpl.DEVICE_PREFIX + uid + DevicesServiceImpl.DOORID_PREFIX + doorId);
//        }
//        Devices device = devicesService.selectDevicesByDeviceId(uid);
//        if (device != null) {
////            MpApplication application = mpApplicationService.getApplicationByAppId(device.getAgentId());
////            if (application != null) {
////                MpAppConfig appConfig = mpAppConfigService.getAppConfigByAppId(device.getAgentId());
////                if (appConfig != null) {
////                    if (!StringUtils.isEmpty(appConfig.getCloseDoorResultCallbackUrl())) {
////                        String errMsg = json.getString("errMsg");
////                        boolean doorStatus = json.getBooleanValue("doorStatus");
////                        // 发送关门通知
////                        JSONObject checkTheDoorResult = new JSONObject();
////                        checkTheDoorResult.put("deviceId", uid);
////                        checkTheDoorResult.put("doorId", doorId);
////                        checkTheDoorResult.put("doorStatus", doorStatus);
////                        checkTheDoorResult.put("errCode", errCode);
////                        checkTheDoorResult.put("errMsg", errMsg);
////                        checkTheDoorResult.put("orderId", orderId);
////                        JSONObject checkCallbackMessage = devicesService.getMessage(device, "checkTheDoorResult", checkTheDoorResult, application.getSecretKey());
////                        rocketMQService.putMQTTMessageToSendUrl(appConfig.getOpenDoorResultCallbackUrl(), checkCallbackMessage);
////                    }
////                }
////                return;
////            }
//        }
//        json.put("key", masterServerKey);
//        //log.info("handlerCheckTheDoorResult 发送url:{}",masterServerUrl + "/cabinet/checkTheDoorResult");
//        rocketMQService.putMQTTMessageToSendUrl(masterServerUrl + "/cabinet/checkTheDoorResult", json);
//    }
//
//    public void handlerMQTTError(String msg, String topic) {
//        try {
//            if (!StringUtils.isEmpty(msg)) {
//                JSONObject jsonObject = JSON.parseObject(msg);
//                String event = jsonObject.getString("event");
//                if ("openTheDoor".equals(event)) {
//                    String biz = jsonObject.getString("biz");
//                    JSONObject bizContent = JSONObject.parseObject(biz);
//                    String orderId = bizContent.getString("orderId");
//                    int doorId = bizContent.getInteger("doorId");
//                    // 发送门锁发送失败报文给服务器
//                    String[] split = topic.split("/");
//                    if (split.length < 1) {
//                        return;
//                    }
//                    String deviceId = split[1];
//                    JSONObject parmas = new JSONObject();
//                    parmas.put("uid", deviceId);
//                    JSONObject bizObject = new JSONObject();
//                    bizContent.put("doorStatus", true);
//                    bizObject.put("doorId", doorId);
//                    bizObject.put("errCode", 1000);
//                    bizObject.put("errMsg", "发送MQTT消息错误");
//                    bizObject.put("orderId", orderId);
//                    parmas.put("biz", bizObject.toJSONString());
//                    handlerCheckTheDoorResult(parmas);
//                }
//            }
//        } catch (Exception mqttException) {
//            log.error("解析MQTT消息错误: {}", mqttException.getMessage());
//            mqttException.printStackTrace();
//        }
//    }
//}
